from typing import Optional
from pydantic import BaseModel, validator


class ApiConfigBase(BaseModel):
    """API配置基础模式"""
    code: Optional[str] = None
    api_url: Optional[str] = None
    api_user: Optional[str] = None
    api_pwd: Optional[str] = None
    api_key: Optional[str] = None
    token: Optional[str] = None
    remarks: Optional[str] = None


class ApiConfigCreate(ApiConfigBase):
    """API配置创建模式"""
    code: str
    api_url: str

    @validator('code')
    def code_not_empty(cls, v):
        if not v or not v.strip():
            raise ValueError('唯一代码不能为空')
        return v.strip()

    @validator('api_url')
    def api_url_not_empty(cls, v):
        if not v or not v.strip():
            raise ValueError('API地址不能为空')
        return v.strip()


class ApiConfigUpdate(ApiConfigBase):
    """API配置更新模式"""
    version: int  # 用于乐观锁控制


class ApiConfigInDBBase(ApiConfigBase):
    """数据库中的API配置模式基类"""
    id: int
    version: int

    class Config:
        orm_mode = True


class ApiConfig(ApiConfigInDBBase):
    """返回给客户端的API配置模式"""
    pass


class ApiConfigInDB(ApiConfigInDBBase):
    """数据库中的API配置模式，完整信息"""
    pass